#include "EventObject.h"

#include <libintl.h>
#include <stdio.h>
#include <stdlib.h>

#define _(String) gettext(String)

void
event_object_init(EventObject *object)
{
	object->finalize  = NULL;
	object->ref_count = 1;
#if EVENT_OBJECT_DEBUG_ALL
	object->debug_flag = true;
#else
	object->debug_flag = false;
#endif
}

void
event_object_addref(epointer any_event_object)
{
	EventObject *object;
	if (!any_event_object)
		return;
	object		   = EVENT_OBJECT(any_event_object);
	object->ref_count += 1;
	if (object->debug_flag) {
		event_debug(EventObject, event_object_addref,
			    "DEBUG Object<%p> ref_count: %d -> %d", object,
			    object->ref_count - 1, object->ref_count);
	}
}

void
event_object_set_finalize(epointer event_object, EventObjectFinalize finalize)
{
	EventObject *object = EVENT_OBJECT(event_object);
	object->finalize    = finalize;
}

void
event_object_unref(epointer any_event_object)
{
	EventObject *object;

	if (!any_event_object)
		return;

	object		   = EVENT_OBJECT(any_event_object);
	object->ref_count -= 1;
	if (object->debug_flag) {
		event_debug(EventObject, event_object_unref,
			    "DEBUG Object<%p> ref_count: %d -> %d", object,
			    object->ref_count + 1, object->ref_count);
	}
	if (object->ref_count > 0)
		return;
	if (object->ref_count < 0) {
		printf(_("Memory error warning: Reference count is less than 0 "
			 "(object<%p> ref: %d)\n"),
		       object, object->ref_count);
	}
	if (object->finalize)
		object->finalize(any_event_object);
	free(any_event_object);
}

EventObject *
event_object_reference(EventObject *object)
{
	if (!object)
		return NULL;
	event_object_addref(object);
	return object;
}

void
event_object_make_debug(EventObject *self)
{
	return_if_fail(self != NULL, event_object_make_debug);
	event_debug(EventObject, event_object_make_debug,
		    "DEBUG Object<%p> make debuged. ref_count: %d", self,
		    self->ref_count);
	self->debug_flag = true;
}
